<template>
  <div class="div-pop" v-show="isGetSkuBuy" @click="close" catchtouchmove="true">    
    <div class="get-sku-buy" catchtap>
      <toast-layer v-if="toastShow" :toastContent="toastContent" :toastType="toastType" toastPosition="absolute"></toast-layer>
      <div class="flex pos-rel">
        <div class="pad-t-15 pad-b-15 pad-r-15">
          <div class="img-box flex flex-center">
            <img v-if="skuImage" :src="skuImage + '?imageView2/1/w/300/h/300'" mode="aspectFill" class="img-item" @click="previewImage(skuImage)"/>
            <van-icon v-else name="photo" class="photo-default" />
          </div>
        </div>
        <!-- 阶梯价 -->
        <div v-if="tempLadderPriceList.length > 0" class="ladder-price-box">
          <div class="ladder-title line-2">
            {{ goods.title }}
          </div>
          <swiper class="swiper-price-box" :current="curLadderIndex">
            <block v-for="(item, index) of tempLadderPriceList" :key="index">
              <swiper-item class="swiper-price-item" :class="item.length === 3 ? 'flex-style-1':'flex-style-2'">
                <div v-for="(subitem, subindex) of item" :key="subindex">
                  <p :class="subitem.isActive ? 'font-red-sku' : 'font-gray-sku'">￥<span>{{subitem.ladderPrice}}</span></p>
                  <span style="text-align: left">{{subitem.ladderNum}}个起批</span>
                </div>
              </swiper-item>
            </block>
          </swiper>
        </div>
        <div v-else>
          <div class="flex-item pad-t-15 pad-b-15">
            <div class="flex flex-column-between height-105">
              <div class="font-red-sku font-24 line-h-1 pad-t-3">
                <span :class="{'price-range': pariceLength >= 13}">
                  <label>{{ goods.priceRange }}</label>
                </span>
                <span class="" v-if="false">
                  <span class="font-15 mar-r-3">¥</span>
                  <label>{{ goods.wholesalePrice }}</label>
                </span>
              </div>
              <div class="title-sku mar-b-8 font-13">
                {{ goods.title }}
              </div>
            </div>
          </div>
        </div>
        <div class="close-btn" @click="close">
          <img v-if="fileSpace" mode="widthFix" class="width-19 height-19" :src="fileSpace + '/images/close-icon-2.png'"/>
        </div>
      </div>
      <!-- 多规格 -->
      <div v-if="skuList.length !== 0">
        <scroll-view scroll-y="" class="clearfix scroll-sky">
          <div class="flex v-align-c sku-list pad-t-9 pad-b-9" v-for="(item, index) in skuList" :key="index">
            <div class="flex-item" @click="onClickGoodsNum(item)">
              <div class="font-15 font-w">{{ item.skuDetail }}</div>
              <div class="font-12 font-color-9">¥ {{ item.wholesalePrice }}</div>
            </div>
            <div class="font-12 font-color-9 pad-r-6">库存：{{ item.stock }}</div>
            <van-stepper v-model="item.goodsNum" :max="item.stock" integer
              :disabled="item.stock === 0 ? true : false" min="0" @change="onChangeGoodsNum($event, item)"/>
          </div>
        </scroll-view>
      </div>
      <!-- 单规格 -->
      <div v-else class="clearfix">
        <div class="flex v-align-c sku-list pad-t-9 pad-b-9">
          <div class="flex-item font-13">购买数量</div>
          <div class="font-12 font-color-9 pad-r-6">库存：{{ goods.stock }}</div>
          <van-stepper v-model="goodsNum" min="1" :max="goods.stock" integer
            :disabled="goods.stock === 0 ? true : false" @change="onChangeGoodsNum($event, '1')"/>
        </div>
      </div>
      <div class="total-bar flex v-align-c font-14 pad-r-15 pad-t-4 pad-b-4 mar-l--20 mar-r--20">
        <span class="flex-item text-align-r font-color-6">共</span>
        <label class="pad-l-3 pad-r-3">{{ selTotalNum }}</label>
        <span class="font-color-6">{{ goods.unit ? goods.unit : '件' }}</span>
        <label class="mar-l-12 mar-r-1">¥</label>
        <label>{{ selTotalPrice }}</label>
      </div>
      <div class="confirm-btn mar-l--20 mar-r--20">
        <div class="btn flex">
          <span class="flex-item" @click="save(isCart)">确定</span>
        </div> 
      </div>
      <div class="pad-10" v-if="isIPhoneX"></div>
    </div>
  </div>
</template>

<script>
  import ToastLayer from '@/components/ToastLayer'
  import {
    addListShoppingCart
  } from '@/api/shop'

  export default {
    components: { ToastLayer },
    data() {
      return {
        goods: {},
        skuList: [],
        isGetSkuBuy: false,
        isComponents: true,
        isCart: true,
        isStock: true,
        selSkuList: [],
        selTotalNum: 0,
        selTotalPrice: 0,
        skuPrice: 0,
        skuId: '',
        skuImage: '',
        stockSkuNum: 0,
        skuDetail: '',
        buyNowBoolean: false,
        SKUResult: {},
        toastShow: false,
        toastType: '',
        toastContent: '',
        goodsNum: 1,
        isWholesale: true,
        tempwholesalePrice: '',
        curLadderIndex: 0
      }
    },
    props: {
      goodsType: {
        type: Number,
        default: 0
      },
      goodsData: {
        type: Object,
        default: {}
      },
      skuList: {
        type: Array,
        default: []
      },
      tempLadderPriceList: {
        type: Array,
        default: []
      }
    },
    computed: {
      isIPhoneX() {
        return this.$utils.isIPhoneX()
      },
      pariceLength() {
        if (this.goods.minWholesalePrice && this.goods.maxPrice) {
          return this.goods.minWholesalePrice.length + this.goods.maxPrice.length
        } else {
          return 0
        }
      }
    },
    mounted() {
    },
    onShow() {
      if (this.$store.state.previewImageFlag) {
        this.$store.commit('setPreviewImageFlag', false)
        return
      }
      this.close()
    },
    beforeMount() {
    },
    methods: {
      show(goods, isCart, type) {
        // 初始化data
        Object.assign(this.$data, this.$options.data())
        this.goods = goods
        this.goodsNum = 1
        // this.selSkuList = []
        if (this.skuList.length === 0) {
          let price = this.tempLadderPriceList.length > 0 ? this.tempLadderPriceList[0][0]['ladderPrice'] : this.goods.wholesalePrice
          this.simpleGoods(price)
        }
        if (this.skuList.length !== 0) {
          this.skuList.forEach(item => {
            item.goodsNum = 0
          })
        }
        if (this.goodsData) {
          this.goods = this.goodsData
        }
        if (type) {
          this.buyNowBoolean = true
        }
        this.isCart = isCart
        this.isGetSkuBuy = true
        this.skuImage = this.goods.images[0]
      },
      close() {
        this.selSkuList = []
        this.goods = {}
        this.isGetSkuBuy = false
        // 阶梯价重置
        for (let i = 0; i < this.tempLadderPriceList.length; i++) {
          for (let subLadderItem of this.tempLadderPriceList[i]) {
            subLadderItem.isActive = false
            this.tempLadderPriceList[0][0].isActive = true
            this.curLadderIndex = 0
          }
        }
      },
      save(booleanVal) {
        this.isCart = booleanVal
        if (this.selSkuList.length === 0) return this.$utils.showToast({ title: '请选择商品规格！' })
        if (this.isCart) {
          addListShoppingCart(this.selSkuList).then((response) => {
            if (response.isError) return
            this.selSkuList = []
            this.$utils.showToast({ title: '已加入购物车', icon: 'success' })
            this.$emit('finished')
          }).catch(() => {
          })
        } else {
          if (this.selTotalNum < this.goods.wholesaleNum) {
            this.toastShow = true
            this.toastType = 'warm'
            if (!this.goods.unit) {
              this.goods.unit = '件'
            }
            this.toastContent = '最少采购' + this.goods.wholesaleNum + this.goods.unit + '起批'
            return
          }
          let paramsAry = []
          // 过滤购买商品数量为0的商品
          this.selSkuList.forEach(item => {
            if (item.goodsNum !== 0) {
              paramsAry.push(item)
            }
          })
          this.selSkuList = paramsAry
          this.$pt.navigateTo({
            url: '/pages/shop/buy/main?goodsId=' + this.goods.goodsId + '&skuList=' +
              JSON.stringify(this.selSkuList) + '&goodsType=' + this.goodsType
          })
        }
        this.close()
        this.isGetSkuBuy = false
      },
      stockLimit(goodsNum, item) {
        this.toastShow = true
        this.toastType = 'warm'
        if (!this.goods.unit) {
          this.goods.unit = '件'
        }
        this.toastContent = '最多采购' + item.stock + this.goods.unit
      },
      changeItemEls(item) {
        this.skuImage = item.imageUrl
        const changeData = '¥' + item.wholesalePrice
        this.$delete(this.goods, 'priceRange')
        this.$set(this.goods, 'priceRange', changeData)
      },
      onClickGoodsNum(item) {
        this.changeItemEls(item)
      },
      onChangeGoodsNum(e, item) {
        let goodsNum = e.mp.detail
        if (item !== '1') {
          // 多规格
          this.changeItemEls(item)
          // 输入商品数量是否超过库存量
          if (goodsNum > item.stock) {
            item.goodsNum = item.stock
            this.stockLimit(goodsNum, item)
            return
          }
          if (this.selSkuList.length !== 0) {
            let skuId = this.selSkuList.map(item => {
              return item.skuId
            })
            if (skuId.includes(item.skuId)) {
              this.selSkuList.forEach((skuItem, skuIndex) => {
                skuItem = item
                skuItem.goodsNum = goodsNum
                skuItem.memberId = this.getShowBuyCard ? this.getCustomerId : this.getMemberId
                skuItem.customerId = this.getShowBuyCard ? this.getCustomerId : this.getMemberId
              })
              this.selSkuList.forEach((selItem, selIndex) => {
                if (selItem.goodsNum === 0) {
                  this.selSkuList.splice(selIndex, 1)
                }
              })
            } else {
              this.setGoodsEls(item, goodsNum)
            }
          } else {
            this.setGoodsEls(item, goodsNum)
          }
          let selTotalNum = 0
          let selTotalPrice = 0
          this.selSkuList.forEach(item => {
            selTotalNum += Number(item.goodsNum)
          })
          // 阶梯价
          if (this.goods.ladderAuth === 1) {
            let tempGoodsLadderPrice = this.getLadderPrice(selTotalNum)
            selTotalPrice += Number(selTotalNum) * Number(tempGoodsLadderPrice)
          } else {
            this.selSkuList.forEach(item => {
              selTotalPrice += Number(item.goodsNum) * Number(item.wholesalePrice)
            })
          }
          this.selTotalNum = Number(selTotalNum)
          this.selTotalPrice = parseInt(selTotalPrice * 100) / 100
        } else {
          // 单规格
          this.goodsNum = goodsNum
          if (this.goods.ladderAuth === 1) {
            let tempGoodsLadderPrice = this.getLadderPrice(goodsNum)
            this.simpleGoods(tempGoodsLadderPrice)
          } else {
            this.simpleGoods(this.goods.wholesalePrice)
          }
        }
      },
      // 处理阶梯价
      getLadderPrice(total) {
        let tempArr = this.goods.ladderPriceList.filter(tempItem => {
          return tempItem.ladderNum <= total
        })
        let tempGoodsLadderPrice = tempArr.length > 0 ? tempArr[tempArr.length - 1]['ladderPrice'] : this.goods.ladderPriceList[0]['ladderPrice']
        this.$set(this.goods, 'curGoosLadderPrice', tempGoodsLadderPrice)
        for (let i = 0; i < this.tempLadderPriceList.length; i++) {
          for (let subLadderItem of this.tempLadderPriceList[i]) {
            if (subLadderItem.ladderPrice === tempGoodsLadderPrice) {
              subLadderItem.isActive = true
              this.curLadderIndex = i
            } else {
              subLadderItem.isActive = false
            }
          }
        }
        return tempGoodsLadderPrice
      },
      simpleGoods(price) {
        this.selTotalNum = this.goodsNum
        let selTotalPrice = 0
        selTotalPrice = Number(this.goodsNum) * Number(price)
        this.selTotalPrice = parseInt(selTotalPrice * 100) / 100
        this.selSkuList = [{
          customerId: this.getCustomerId,
          memberId: this.getCustomerId,
          goodsId: this.goods.goodsId,
          goodsNum: this.goodsNum,
          wholesalePrice: this.goods.wholesalePrice,
          skuCode: '',
          skuDetail: '',
          skuId: ''
        }]
      },
      setGoodsEls(item, goodsNum) {
        item.goodsNum = goodsNum
        item.memberId = this.getCustomerId
        item.customerId = this.getCustomerId
        this.selSkuList.push(item)
      },
      previewImage(current) {
        this.$pt.previewImage({
          urls: [current],
          current: current,
          success: res => {
            this.$store.commit('setPreviewImageFlag', true)
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
.get-sku-buy {
  width: 375px;
  box-sizing: border-box;
  padding: 0 15px;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 990;
  .close-btn {
    position: absolute;
    width: 36px;
    height: 36px;
    right: -8px;
    top: 9px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .border-b {
    border-bottom: #f7f7f7 1px solid;
  }
  .scroll-sky {
    max-height: 286px;
  }
  .title-sku {
    max-height: 38px;
    line-height: 1.5;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }
  .font-red-sku {
    color: #ff5540;
  }
  .font-gray-sku {
    color: #999999;
  }
  .sku-list {
    border-bottom: #f4f4f4 1px solid;
    &:last-child {
      border-bottom: none;
    }
    /deep/ .van-stepper {
      .van-stepper__input {
        background: #fff !important;
      }
    }
  }
  .total-bar {
    color: #ff5540;
    box-shadow: 0px 0px 6px rgba(206, 206, 206, 0.3);
  }
  .stock-num {
    font-size: 12px;
    padding-top: 24px;
    color: #949494;
  }
  .sku-detail {
    font-size: 12px;
    padding-top: 1px;
    color: #949494;
  }
}

.img-box{
  width: 105px;
  height: 105px;
  background: #f7f8fa;
  border-radius: 10px;
  .photo-default{
    font-size: 30px;
    color: #dcdee0;
  }
}

.img-item {
  width: 105px;
  height: 105px;
  border-radius: 10px;
}

.goods-title {
  height: 50px;
  overflow: hidden;
}

.confirm-btn {
  color: #fff;
  text-align: center;
  .btn {
    overflow: hidden;
    border-radius: 0;
    span {
      display: block;
      height: 50px;
      line-height: 50px;
      font-size: 16px;
      color: #fff;
      background: linear-gradient(to right, #ff8e4b, #ff4e25);
      cursor: pointer;
    }
  }
}

.sku-prop-value {
  background-color: #f2f2f2;
  padding: 4px 13px;
  border-radius: 100px;
  margin-right: 15px;
  margin-top: 5px;
  min-width: 30px;
  color: #333333;
}

.sel-prop-value {
  background-color: #ffd005;
}
.disable-prop-value {
  color: #d2d2d2;
  background-color: #f7f7f7;
}
.line-h-1 {
  line-height: 1;
}
.price-range {
  display: block;
}
.goods-price-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100%;
  padding-top: 40rpx;
  .goods-title {
    width: 80%;
    font-size: 26rpx;
    color: #333333;
  }
}
.ladder-price-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  .ladder-title {
    margin-top: 30rpx;
    width: 90%;
    font-size: 26rpx;
  }
  .swiper-price-box {
    height: 100rpx;
    background: #fff;
    width: 100%;
    box-sizing: border-box;
    .flex-style-1 {
      display: flex;
      justify-content: space-between;
    }
    .flex-style-2 {
      display: flex;
      & > div:nth-child(2) {
        margin-left: 30px;
      }
    }
    .swiper-price-item {
      & > div {
        display: flex;
        justify-content: center;
        flex-direction: column;
        height: 100%;
        p {
          font-size: 24rpx;
          span {
            font-size: 32rpx;
          }
        }
        & > span {
          color: #666666;
          font-size: 20rpx;
          margin-top: -5rpx;
        }
      }
    }
  }
}
</style>
